//
//  KKVideoDetailController.m
//  DoMi
//
//  Created by 康凯 on 2016/11/9.
//  Copyright © 2016年 kk. All rights reserved.
//

#import "KKVideoDetailController.h"
#import "KKStudyHttp.h"
#import "KKVideoDetail.h"
#import "KKIntroductionView.h"
#import "KKCommentView.h"
#import "KKRelateCell.h"
#import "KKItemListController.h"
#import "KKStudyItem.h"
#import "KKBuyVideoM.h"
#import "KKVideoPayDialog.h"
#import "KKPayInfoM.h"
#import "WXApi.h"
#import <AlipaySDK/AlipaySDK.h>
#import "KKPdfCollectionCell.h"
#import "KKPdfView.h"
#import "KKCustomVideoView.h"
#import "IQKeyboardManager.h"
#import "KKMyHttp.h"
#define VIDEO_HEIGHT self.fatherView.frame.size.height
#define M_PI 3.14159265358979323846264338327950288

#define ALIPAY_SCHEMA @"KKDoMiAlipay"
@interface KKVideoDetailController ()<ZFPlayerDelegate,collectionCellDelegate,PdfViewClickDelegate>
@property (nonatomic, strong) ZFPlayerModel *playerModel;
//@property (weak, nonatomic) IBOutlet ZFPlayerView *playerView;
@property (weak, nonatomic) IBOutlet UIButton *introductionBtn;
@property (weak, nonatomic) IBOutlet UIButton *commentBtn;

@property (weak, nonatomic) IBOutlet UIView *container;
//简介
@property (strong, nonatomic) KKIntroductionView *introductionView;
//评论
@property (strong, nonatomic) KKCommentView *commentView;

@property(strong,nonatomic) NSArray *items;
@property(strong,nonatomic) KKBuyVideoM *buyInfo;

@property (strong, nonatomic)ZFPlayerView *playerView;

@property (weak, nonatomic) IBOutlet UIView *inputView;
@property (weak, nonatomic) IBOutlet UITextField *input;
@property (weak, nonatomic) IBOutlet UIView *fatherView;

@property (copy,nonatomic)NSString *buyItem;
@property (assign,nonatomic)size_t pdfCount;
@property (strong,nonatomic)NSMutableArray *pdfPages;
@property (strong,nonatomic)NSMutableArray *pdfBigPages;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pdfHeight;
@property (weak, nonatomic) UICollectionViewFlowLayout *flowLayout;

@property (weak, nonatomic) KKCustomVideoView *videoView;
@property (assign, nonatomic) int fullVideoFlag;
@property (assign, nonatomic) int fullFlag;

@property (weak, nonatomic) UIScrollView *scrollView;
@property (weak, nonatomic) UIScrollView *scrollFullView;
@property (copy, nonatomic) NSString *pdfImg;
@property (weak, nonatomic) UIImageView *pdfImgView;
@property (weak, nonatomic) UIImageView *pdfFullImgView;
@end

@implementation KKVideoDetailController
#pragma mark 懒加载
- (ZFPlayerModel *)playerModel
{
    if (!_playerModel) {
        _playerModel = [[ZFPlayerModel alloc] init];
    }
    return _playerModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"视频详情";
    [self initView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar=NO;
    [self setNavWhite];
//    [self registerForKeyboardNotifications];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDeviceOrientationChange) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.playerView pause];
    [IQKeyboardManager sharedManager].enableAutoToolbar=YES;
//    [IQKeyboardManager sharedManager].enable = YES;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

-(void)initView{
    //左侧排行榜
    UIButton *leftBtn = [[UIButton alloc ]initWithFrame:CGRectMake(0, 0, 12, 20)];
    [leftBtn setImage:[UIImage imageNamed:@"back_blue"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    
    self.fullFlag=0;
    self.introductionBtn.selected=YES;
    self.commentBtn.selected=NO;
    self.inputView.hidden=YES;
    [self getVideoDetail];
    [self getStudyItem];
    [self getRelateVideoList];
    
    CGFloat viewHeight= screenHeight-self.topHeight-274;
    self.introductionView=[[[NSBundle mainBundle] loadNibNamed:@"KKIntroductionView" owner:self options:nil] lastObject];
    self.introductionView.height=viewHeight;
    [self.introductionView initView];
    self.commentView=[[[NSBundle mainBundle] loadNibNamed:@"KKCommentView" owner:self options:nil] lastObject];
    [self.commentView initView:viewHeight];
    self.commentView.hidden=YES;
    self.introductionView.hidden=NO;
    [self.container addSubview:self.introductionView];
    [self.container addSubview:self.commentView];
    
    NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(wXPayNotice:) name:@"wxPaySuccess" object:nil];
}

/**
 *  屏幕方向发生变化会调用这里
 */
- (void)onDeviceOrientationChange
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    KKLog(@"change---->%ld",(long)orientation);
    if(orientation==UIDeviceOrientationPortrait){
        if(self.fullFlag==1){
            self.fullFlag=0;
            [self initVideoPdf];
            [self.scrollFullView removeFromSuperview];
            [self.pdfFullImgView removeFromSuperview];
        }
        
    }else{
        self.fullFlag=1;
        UIScrollView *scrollView1=[[UIScrollView alloc] initWithFrame:CGRectMake(-150,150, screenWidth,screenHeight)];
        scrollView1.backgroundColor=[UIColor greenColor];
        scrollView1.transform=CGAffineTransformIdentity;
        self.scrollFullView=scrollView1;
        self.scrollFullView.hidden=YES;
        self.scrollFullView.transform=CGAffineTransformMakeRotation(M_PI/2);
        scrollView1.backgroundColor=[UIColor redColor];
        scrollView1.pagingEnabled=YES;
        scrollView1.scrollEnabled=YES;
        scrollView1.showsHorizontalScrollIndicator=YES;
        scrollView1.showsVerticalScrollIndicator=NO;
        scrollView1.contentSize=CGSizeMake(self.pdfPages.count*screenWidth, 100);
        for (int i=0; i<self.pdfPages.count; i++) {
            KKPdfView *pdf=self.pdfPages[i];
            pdf.delegate=self;
            pdf.frame=CGRectMake(screenWidth*i, 0, screenWidth,screenHeight);
            [scrollView1 addSubview:pdf];
        }
        [appWindow addSubview:scrollView1];
        
        
        UIImageView *pdfFullThum=[[UIImageView alloc] initWithFrame:CGRectMake(screenHeight-self.statusHeight-110,screenWidth-130, 150, 80)];
        self.pdfFullImgView.transform=CGAffineTransformIdentity;
        self.pdfFullImgView=pdfFullThum;
        self.pdfFullImgView.transform=CGAffineTransformMakeRotation(M_PI/2);
        [appWindow addSubview:pdfFullThum];
        [pdfFullThum sd_setImageWithURL:[NSURL URLWithString:self.pdfImg]];
        [pdfFullThum setUserInteractionEnabled:YES];
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pdfImgClick1)];
        [pdfFullThum addGestureRecognizer:tap];
    }
}
-(void)pdfClick{
    if(self.fullFlag==0){
        self.scrollView.hidden=YES;
        self.pdfImgView.hidden=NO;
    }else{
        self.scrollFullView.hidden=YES;
        self.pdfFullImgView.hidden=NO;
    }
}
#pragma mark 初始化数据
-(void)initData:(KKVideoDetail *)data{
    self.playerModel.fatherView=self.fatherView;
    self.playerModel.title = data.videoname;
    self.playerModel.videoURL =[NSURL URLWithString:data.videopath];
    self.playerModel.placeholderImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:data.cover]]];
    [self initVideo];
    
    if(![KKAppUtils isEmptyString:data.notespath]){
        CGPDFDocumentRef document=GetPDFDocumentRef(data.notespath);
        self.pdfCount = CGPDFDocumentGetNumberOfPages(document);
        self.pdfPages=[NSMutableArray array];
        self.pdfBigPages=[NSMutableArray array];
        for (int i=0; i<self.pdfCount; i++) {
            KKPdfView *pdf=[[KKPdfView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 240)];
            pdf.backgroundColor=[UIColor whiteColor];
            pdf.currentPage=i+1;
            pdf.pdf=document;
            [self.pdfPages addObject:pdf];
        }
        [self initVideoPdf];
    }
}
#pragma mark 视频上pdf
-(void)initVideoPdf{
    UIScrollView *scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0,2, screenWidth, 240)];
    self.scrollView=scrollView;
    self.scrollView.hidden=YES;
    //    scrollView.backgroundColor=[UIColor redColor];
    scrollView.pagingEnabled=YES;
    scrollView.scrollEnabled=YES;
    scrollView.showsHorizontalScrollIndicator=YES;
    scrollView.showsVerticalScrollIndicator=NO;
    scrollView.contentSize=CGSizeMake(screenWidth*self.pdfPages.count, 240);
    for (int i=0; i<self.pdfPages.count; i++) {
        KKPdfView *pdf=self.pdfPages[i];
        pdf.delegate=self;
        pdf.frame=CGRectMake(screenWidth*i, 0, screenWidth, 240);
        [scrollView addSubview:pdf];
    }
    [self.view addSubview:scrollView];
    
    UIImageView *pdfThum=[[UIImageView alloc] initWithFrame:CGRectMake(screenWidth-105,4, 100, 60)];
    self.pdfImgView=pdfThum;
    [self.view addSubview:pdfThum];
    [pdfThum sd_setImageWithURL:[NSURL URLWithString:self.pdfImg]];
    [pdfThum setUserInteractionEnabled:YES];
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pdfImgClick)];
    [pdfThum addGestureRecognizer:tap];
}

#pragma mark pdf图片点击
-(void)pdfImgClick{
    self.pdfImgView.hidden=YES;
    self.scrollView.hidden=NO;
}
#pragma mark pdf全屏图片点击
-(void)pdfImgClick1{
    self.pdfFullImgView.hidden=YES;
    self.scrollFullView.hidden=NO;
}
#pragma mark 视频相关控制
-(void)initVideo{
    self.playerView = [[ZFPlayerView alloc] init];
    [self.view addSubview:self.playerView];
    [self.playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.right.equalTo(self.view);
        // Here a 16:9 aspect ratio, can customize the video aspect ratio
        make.height.equalTo(self.playerView.mas_width).multipliedBy(9.0f/16.0f);
    }];
    // control view（you can custom）
    KKCustomVideoView *videoView=[[KKCustomVideoView alloc] init];
    self.videoView=videoView;
    videoView.videoId=self.videoId;
    __weak typeof(self) weakSelf=self;
    videoView.payTypeBlock=^(NSString *type,NSString *buyItem){
        if([type isEqualToString:@"ali"]){
            weakSelf.buyItem=buyItem;
            [weakSelf payInfo:@"ali"];
        }else if([type isEqualToString:@"wx"]){
            weakSelf.buyItem=buyItem;
            [weakSelf payInfo:@"wx"];
        }else{
            [weakSelf jiFenPay];
        }
    };
    videoView.fullScreenBlock=^(UIButton *btn){
        
    };
    [self.playerView playerControlView:videoView playerModel:self.playerModel];
    
    // 设置代理
    self.playerView.delegate = self;
    
    // 打开下载功能（默认没有这个功能）
    self.playerView.hasDownload    = NO;
    // 打开预览图
    self.playerView.hasPreviewView = YES;
}

- (void)zf_playerBackAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma makr 获取pdf路径
CGPDFDocumentRef GetPDFDocumentRef(NSString *filename)
{
    NSURL *url =[NSURL URLWithString:filename];//将传入的字符串转化为一个NSURL地址
    
    CFURLRef refURL = (__bridge_retained CFURLRef)url;//将的到的NSURL转化为CFURLRefrefURL备用
    
    CGPDFDocumentRef document =CGPDFDocumentCreateWithURL(refURL);//通过CFURLRefrefURL获取文件内容
    CFRelease(refURL);//过河拆桥，释放使用完毕的CFURLRefrefURL，这个东西并不接受自动内存管理，所以要手动释放
    if(document){
        return document;
    }else{
        printf("加载失败!\n");
        return NULL;
    }
    return document;
}

#pragma mark 简介点击
- (IBAction)introductionBtn:(id)sender {
    self.introductionBtn.selected=YES;
    self.commentBtn.selected=NO;
    self.introductionView.hidden=NO;
    self.commentView.hidden=YES;
    self.inputView.hidden=YES;
    
}
#pragma mark 评论点击
- (IBAction)commentBtn:(id)sender {
    self.introductionBtn.selected=NO;
    self.commentBtn.selected=YES;
    self.commentView.hidden=NO;
    self.introductionView.hidden=YES;
    self.inputView.hidden=NO;
    [self getCommentList];
}

#pragma mark 通知接受
-(void)wXPayNotice:(NSNotificationCenter *)center{
    [self toast:@"视频购买成功"];
}

//#pragma mark collectionview代理
//-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
//    return self.pdfPages.count;
//}
//
//-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    KKPdfCollectionCell *cell = (KKPdfCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"KKPdfCollectionCell" forIndexPath:indexPath];
//    cell.cellTapDelegate=self;
//    KKPdfView *pdf=self.pdfPages[indexPath.row];
//    if([[UIApplication sharedApplication] statusBarOrientation]==UIDeviceOrientationPortrait){
//        CGRect temp=pdf.frame;
//        temp.size.height=240;
//        temp.size.width=screenWidth;
//        pdf.frame=temp;
//    }else{
//        CGRect temp=pdf.frame;
//        temp.size.height=screenHeight;
//        temp.size.width=screenWidth;
//        pdf.frame=temp;
//    }
//    cell.showView=pdf;
//    return cell;
//}
//
//
//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//    if([[UIApplication sharedApplication] statusBarOrientation]==UIDeviceOrientationPortrait){
//
//        return CGSizeMake(screenWidth, 240);
//    }else{
//
//        return CGSizeMake(screenWidth, screenHeight);
//    }
//}
//
//-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
//    return UIEdgeInsetsMake(0, 0, 0, 0);
//}
//
//- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView {
//    for(UIView *view in self.collectionView.subviews) {
//        if([view isKindOfClass:[KKPdfCollectionCell class]]) {
//            KKPdfCollectionCell *cell = (KKPdfCollectionCell*)view;
//            [cell.contentScrollView setZoomScale:1.0];
//        }
//    }
//}
//
//- (void)collectioncellTaped:(KKPdfCollectionCell*)cell {
//    if(self.isScalePdf){
//        if(self.fullVideoFlag==1){
//            self.collectionView.frame=CGRectMake(screenHeight-95,screenWidth-160, 80, 150);
//        }else{
//            self.collectionView.frame=CGRectMake(screenWidth-105,4, 100, 60);
//        }
//    }else{
//        if(self.fullVideoFlag==1){
//            self.collectionView.frame=CGRectMake(0, 0, screenHeight, screenWidth);
//            [self.collectionView reloadData];
//        }else{
//            self.collectionView.frame=CGRectMake(0, 2, screenWidth, VIDEO_HEIGHT);
//        }
//    }
//    self.isScalePdf=!self.isScalePdf;
//
//}


//#pragma mark 弹出支付dialog
//-(void)showBuyVideoDialog{
//    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:@"确定购买视频" preferredStyle:UIAlertControllerStyleAlert];
//
//    [alert addAction:[UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self.navigationController popViewControllerAnimated:YES];
//    }]];
//    [alert addAction:[UIAlertAction actionWithTitle:@"支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        //支付
//        KKVideoPayDialog *pay=[[[NSBundle mainBundle] loadNibNamed:@"KKVideoPayDialog" owner:self options:nil] lastObject];
//        pay.buyInfo=self.buyInfo;
//        pay.jiFenPayBlock=^(){
//            [self jiFenPay];
//        };
//        pay.wXPayBlock=^(NSString *type){
//            self.buyItem=type;
//            [self payInfo:@"wx"];
//        };
//        pay.aliPayBlock=^(NSString *type){
//            self.buyItem=type;
//            [self payInfo:@"ali"];
//        };
//        [pay show];
//    }]];
//    [self presentViewController:alert animated:YES completion:nil];
//}

#pragma mark 点击--返回
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 接口--视频详情信息获取
-(void)getVideoDetail{
    [self showDialog];
    NSDictionary *params=@{@"uid":self.uid,@"token":self.token,@"videoid":self.videoId};
    [KKStudyHttp getVideoDetail:params success:^(id data) {
        [self dismissDialog];
        KKVideoDetail *videoDetail=data;
        self.pdfImg=videoDetail.notesimgpath;
        [self initData:data];
        [self.introductionView refreshData:0 setData:data];
    } failure:^(NSError *error) {
        [self dismissDialog];
    }];
}

#pragma mark 接口--获取头部item
-(void)getStudyItem{
    NSDictionary *params=@{@"uid":self.uid,@"token":self.token};
    [KKStudyHttp getTopItem:params success:^(NSArray *datas) {
        self.items=datas;
        [self.introductionView refreshData:1 setData:datas];
    } failure:^(NSError *error) {
    }];
}

#pragma mark 接口--相关课程列表
-(void)getRelateVideoList{
    [KKStudyHttp getRelateVideoList:self.videoId success:^(NSArray *datas) {
        [self.introductionView refreshData:2 setData:datas];
    } failure:^(NSError *error) {
    }];
}

#pragma mark 接口--评论列表
-(void)getCommentList{
    [self showDialog];
    NSDictionary *params=@{UID_KEY:UID,TOKEN_KEY:TOKEN,@"commenttype":@"v",@"number":self.videoId};
    [KKStudyHttp getCommentList:params success:^(NSArray *datas) {
        [self.commentView refreshData:datas flag:@"0"];
        [self dismissDialog];
    } failure:^(NSError *error) {
        [self dismissDialog];
    }];
}

//#pragma mark 接口--获取视频购买信息
//-(void)getVideoBuyInfo{
//    [KKStudyHttp getVideoBuyInfo:self.videoId success:^(id datas) {
//        self.videoView.buyInfo=datas;
//    } failure:^(NSError *error) {
//        
//    }];
//}
#pragma mark 接口--发表评论
-(void)addComment{
    [self showDialog];
    NSDictionary *params=@{UID_KEY:UID,TOKEN_KEY:TOKEN,@"commenttype":@"v",@"number":self.videoId,@"commentcontent":self.input.text};
    [KKStudyHttp addComment:params success:^(id data) {
        [self dismissDialog];
        [self toast:@"评论成功"];
        [self.view endEditing:YES];
        [self getCommentList];
    } failure:^(NSError *error) {
        [self dismissDialog];
    }];
}
#pragma mark 接口--积分支付
-(void)jiFenPay{
    [KKStudyHttp payJiFenVideo:self.videoId success:^(id data) {
        [self toast:@"支付成功"];
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark 接口--支付信息
-(void)payInfo:(NSString *)type{
    NSDictionary *params=@{UID_KEY:UID,TOKEN_KEY:TOKEN,@"buytype":type,@"videoid":self.videoId,@"type":self.buyItem};
    [KKStudyHttp getPayVideoInfo:params success:^(id data) {
        if([type isEqualToString:@"wx"]){
            KKPayInfoM *payInfo=[KKPayInfoM mj_objectWithKeyValues:data];
            //调起微信支付
            PayReq* req = [[PayReq alloc] init];
            req.partnerId = payInfo.partnerid;
            req.prepayId = payInfo.prepayid;
            req.nonceStr = payInfo.noncestr;
            req.timeStamp = payInfo.timestamp.intValue;
            req.package = payInfo.package;
            req.sign = payInfo.sign;
            [WXApi sendReq:req];
        }else{
            // 调用支付结果开始支付
            [[AlipaySDK defaultService] payOrder:data fromScheme:ALIPAY_SCHEMA callback:^(NSDictionary *resultDic) {
                NSLog(@"reslut ====== %@",resultDic);
            }];
        }
    } failure:^(NSError *error) {
        
    }];
}


#pragma mark - keyboardHight
- (void)registerForKeyboardNotifications
{
    //监听键盘出现
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardDidShowNotification object:nil];
    //监听键盘隐藏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHidden) name:UIKeyboardWillHideNotification object:nil];
    
}

//实现当键盘出现的时候计算键盘的高度大小。用于输入框显示位置
- (void)keyboardShow:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    //获取键盘高度
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    [UIView animateWithDuration:0 animations:^{
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        self.inputView.transform=CGAffineTransformMakeTranslation(0, -kbSize.height);
    } completion:nil];
}

//当键盘隐藏的时候
- (void)keyboardHidden
{
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView animateWithDuration:0 animations:^{
        self.inputView.transform=CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        self.input.text=@"";
    }];
}

- (IBAction)keyboardHiddenClick:(id)sender {
    [self.view endEditing:YES];
}

- (IBAction)sendClick:(id)sender {
    [KKMyHttp userCheck:^(id data) {
        if([KKAppUtils isEmptyString:self.input.text]){
            [self toast:@"请输入评论内容"];
            return;
        }
        [self addComment];
    } failure:^(NSError *error) {
        
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

@end
